package com.winexpress.product;

import com.winexpress.util.Log;
import com.winexpress.util.SessionAttributes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceRef;

@MultipartConfig
@WebServlet(name = "ProductManagement", urlPatterns = {"/productManagement/*"})
public class ProductManagement extends HttpServlet {

    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/WineXpress-war/ProductManagementWS.wsdl")
    private ProductManagementWS_Service service;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ProductManagement Servlet");
        response.setContentType("text/html;charset=UTF-8");
        try {
            RequestDispatcher dispatcher;
            ServletContext servletContext = getServletContext();
            String page = request.getPathInfo().substring(1);
            System.out.println(page);

            HttpSession session = request.getSession();
             if (session.getAttribute(SessionAttributes.USER_ID) == null || session.getAttribute(SessionAttributes.IS_ADMIN) == null ||session.getAttribute(SessionAttributes.IS_ADMIN).toString().equals("false")) {
                response.sendRedirect("/WineXpressClient/loginFail.jsp");
                 System.out.println(session.getAttribute(SessionAttributes.IS_ADMIN));
                return;
            }      

            ProductManagementWS port = service.getProductManagementWSPort();

            //redirect to manageWine
            if ("re".equals(page)) {
                List<Wine> list = port.listWines();
                session.setAttribute("winesList", list);
                
                session.setAttribute("wineCategoryList",this.getCategoryList(list));
                response.sendRedirect("/WineXpressClient/manageWines.jsp");
                return;
            }//add wine
            else if ("addWine".equals(page)) {
                List<Category> list = port.listCategory();
                request.setAttribute("categoryList", list);
            } //load edit wine  */
            else if ("loadEditWine".equals(request.getParameter("edit"))) {
                String wineID = request.getParameter("editWineID");

                Wine w = port.getWine(new Long(wineID).longValue());
                request.setAttribute("wine", w);

                Category c = port.findCategory(w.getId().toString());
                request.setAttribute("category", c);

                List<Category> list = port.listCategory();
                request.setAttribute("categoryList", list);
            } //delete wine 
            else if ("deleteWine".equals(request.getParameter("delete"))) {
                String deleteID = request.getParameter("deleteID");
                Boolean isDelete = port.deleteWine(new Long(deleteID));
                System.out.println("***********");
                System.out.println(isDelete);
                request.setAttribute("isDelete", isDelete);
                Log.info("adminID = " + SessionAttributes.USER_ID  + "delete wine "+deleteID);
            } //relist wine
            else if ("relistWine".equals(request.getParameter("relist"))) {
                String relistID = request.getParameter("relistID");
                Boolean isRelist = port.relistWine(new Long(request.getParameter("relistID")));
                request.setAttribute("isRelist", isRelist);
                Log.info("adminID = " + SessionAttributes.USER_ID  + "delete wine "+relistID);
            }

            List<Wine> list = port.listWines();
            session.setAttribute("winesList", list);

            dispatcher = servletContext.getNamedDispatcher(page);

            if (dispatcher == null) {
                dispatcher = servletContext.getNamedDispatcher("Error");
            }

            dispatcher.forward(request, response);
        } catch (Exception ex) {
            log("Exception in ProductManagement servlet");
            log(ex.toString());
        }
    }
    
    private List<Category> getCategoryList(List<Wine> list){
        ProductManagementWS port = service.getProductManagementWSPort();
        List<Category> categoryList = new ArrayList<>();
        for (int i=0;i<list.size();i++){
            Wine w = (Wine) list.get(i);
            Category c = port.findCategory(w.getId().toString());
            categoryList.add(c);
        }
        return categoryList;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
